package com.agileai.esb.smc.controller.monitor;

import java.util.ArrayList;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.analysis.WebServiceStatManage;
import com.agileai.esb.wsmodel.WSErrorMsg;
import com.agileai.esb.wsmodel.WSRuntimeAnalysis;
import com.agileai.esb.wsmodel.WSRuntimeStat;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;

public class WSRuntimeErrorsHandler
        extends BaseHandler {
    public WSRuntimeErrorsHandler() {
        super();
    }
    
	public ViewRenderer prepareDisplay(DataParam param){
		String appName = param.get("appName");
		String serviceId = param.get("serviceId"); 
		List<DataRow> records = new ArrayList<DataRow>();
		WSRuntimeStat runtimeStat = WSRuntimeAnalysis.geInstance(false).getRuntimeStat(appName,serviceId);
		if (runtimeStat != null){
			List<WSErrorMsg> errorMsgs = runtimeStat.getErrorMessages();
			for (int i = 0;i < errorMsgs.size();i++){
				WSErrorMsg errorMsg = errorMsgs.get(i);
				DataRow row = new DataRow();
				row.put("startTime",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL,errorMsg.getStartTime()));
				row.put("errorMsg",errorMsg.getMessageBody());
				row.put("soapXML",errorMsg.getReqSoapXML());
				records.add(row);
			}
		}
		this.setRsList(records);
		return new LocalRenderer(getPage());
	}    
    
	@PageAction
    public ViewRenderer showHistoryError(DataParam param){
		String sdate = param.get("sdate");
		String edate = param.get("edate");
		String appName = param.get("appName");
		String serviceId = param.get("serviceId"); 
		
		WebServiceStatManage service = lookupService(WebServiceStatManage.class);
		List<DataRow> records = service.findWsErrorRecords(sdate, edate,appName, serviceId);
		if (records != null){
			for (int i = 0;i < records.size();i++){
				DataRow row = records.get(i);
				row.put("startTime",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL,row.getTimestamp("ERROR_TIME")));
				row.put("errorMsg",row.get("ERROR_INFO"));
				row.put("soapXML",row.get("REQ_SOAP_MSG"));
			}
		}
		this.setRsList(records);
		return new LocalRenderer(getPage());
	}        
    
    
    protected void processPageAttributes(DataParam param) {
    }
}
